<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>电力智能巡检系统</span>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="工号" prop="jobNumber">
          <el-input v-model="form.jobNumber" placeholder="请输入工号" prefix-icon="el-icon-phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" prefix-icon="el-icon-lock"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="rememberMe">记住账号密码</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { login } from '../api/user';
import { useStore } from 'vuex'

const store = useStore()

const form = reactive({
  jobNumber: '',
  password: ''
});
const rememberMe = ref(false);

const rules = {
  jobNumber: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

const ruleForm = ref(null);
const router = useRouter();

onMounted(() => {
  const savedjobNumber = localStorage.getItem('jobNumber');
  const savedPassword = localStorage.getItem('password');
  if (savedjobNumber && savedPassword) {
    form.jobNumber = savedjobNumber;
    form.password = savedPassword;
    rememberMe.value = true;
  }
});

const submitForm = async () => {
  try {
    const valid = await ruleForm.value.validate()
    if (valid) {
      if (rememberMe.value) {
        localStorage.setItem('jobNumber', form.jobNumber)
        localStorage.setItem('password', form.password)
      } else {
        localStorage.removeItem('jobNumber')
        localStorage.removeItem('password')
      }
      
      const response = await login(form)
      console.log('登录成功:', response)
      
      if (response) {
        const { token, userInfo } = response.data
        sessionStorage.setItem('token', token)
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        const roleId = userInfo.roleId
        console.log('roleId:', roleId)
        await store.dispatch('permission/generateRoutes', roleId)

        store.state.permission.addRoutes.forEach((route: any) => {
          router.addRoute(route)
        })

        router.push('/dashboard')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '服务器错误')
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #74b9ff, #a29bfe);
}

.box-card {
  width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
}

.card-header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

.register-link {
  text-align: center;
  margin-top: 10px;
}

.demo-ruleForm {
  margin-top: 10px;
  width: 90%;
}

.login-button {
  width: 100%;
  background: linear-gradient(45deg, #0984e3, #74b9ff);
  color: white;
  border: none;

}

.login-button:hover {
  background: linear-gradient(45deg, #74b9ff, #0984e3);
}
</style>
